<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// | Date: 2019/03/15
// | Time:上午 10:26
// | 用于网页微信登录，扫码或微信在线自动登录
// +----------------------------------------------------------------------
namespace plugins\xiongyi\controller;

use cmf\controller\PluginBaseController;
use plugins\xiongyi\lib\WechatOauth2;
//use think\Db;
use think\facade\Db;
use plugins\xiongyi\lib\User;
use think\exception\HttpException;

class Wechat1Controller extends PluginBaseController
{
    /**
     * 微信登录链接
     * https://f.kjdll.cn:9999/plugin/xiongyi/wechat/login
     * @return \think\response\Redirect
     * @throws \Exception
     */
    public function login()
    {
        $wechatOauth2 = new WechatOauth2();
        $config       = $this->getPlugin()->getConfig();
        $wechatOauth2->setAppKey($config['app_id']);
        $wechatOauth2->setAppSecret($config['app_secret']);
        //$url = cmf_plugin_url('WechatLogin://wechat/callback', [], true);
        $url = "https://f.kjdll.cn:9999/plugin/xiongyi/wechat1/callback2025";        //回调地址，不须要url_encode
        //$url = "https%3A%2F%2Ff.kjdll.cn%3A9999%2Fplugin%2Fwechat_login%2Fwechat%2Fcallback";
        $wechatOauth2->setCallback($url);

        return redirect($wechatOauth2->getRequestCodeURL());
    }

    public function logout()
    {
        session(null);
        /**修改成后台用户登陆 END*/

        $this->redirect("/", 302, '');
    }

    /**
     * 第三方登录授权回调地址，用于给dhgx.kjdll.cn用于扫码后登录使用，将扫码登录的用户信息传给dhgx.kjdll.cn
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public function callback2025()
    {
        //var_dump($this->request->param());
        /**
         * { ["code"]=> string(32) "031ag00w3gJMv43klm1w3p9iGK0ag00K" 
         * ["state"]=> string(5) "STATE" 
         * ["_plugin"]=> string(12) "wechat_login" 
         * ["_controller"]=> string(6) "wechat" 
         * ["_action"]=> string(8) "callback" } 
         */

        $code = $this->request->param('code');
        if (empty($code)) {
            $this->error('参数不正确');
        }
        $wechatOauth2 = new WechatOauth2();
        $config       = $this->getPlugin()->getConfig();
        $wechatOauth2->setAppKey($config['app_id']);
        $wechatOauth2->setAppSecret($config['app_secret']);
        //var_dump("appid");
        //var_dump($config['app_id']);
        //var_dump("app_secret");
        //var_dump($config['app_secret']);
        $token = null;
        try {
            $token = $wechatOauth2->getAccessToken($code);
        } catch (\Exception $e) {
            $this->error('登录失败1！' . $e->getMessage(), '/');
        }
        //var_dump($token);
        //获取当前登录用户信息
        if (!is_array($token)) {
            $this->success('登录失败1！', '/plugin/xiongyi/index/login');
        }

        $data = $wechatOauth2->call('sns/userinfo');
        //var_dump($data);
        /**
         * array(10) { 
         * ["openid"]=> string(28) "ocs7O67mv5obM2xjY0F3Xzv26XtA" 
         * ["nickname"]=> string(12) "夕阳余晖" 
         * ["sex"]=> int(0) ["language"]=> string(0) "" 
         * ["city"]=> string(0) "" 
         * ["province"]=> string(0) "" 
         * ["country"]=> string(0) "" 
         * ["headimgurl"]=> string(152) "https://thirdwx.qlogo.cn/mmopen/vi_32/D9hhtg7QVjfHAgRvdk59TfbscOXEVgkQu1v4reLZpE3JQEcq2DbPJqyiakjd8a7R4w2fShAFNBkDzL6qYMxWpF5L15Y4ia7MT5pDV1eEqeMiag/132" 
         * ["privilege"]=> array(0) { } 
         * ["unionid"]=> string(28) "opKXO61L5ZYgdvwEoOiw35bCIYCs" }    ////同一个开放平台添加的web页和小程序，获得的unionid是一样的
         */

        //cmf_dhgxlive_user
        $userInfo = [
            'login_time' => time(),
            'login_ip'   => get_client_ip(0, true),
            'app_id'    => $config['app_id'],   //将APP_ID也传给写入到third_party_user表，以防后面多个应用接入使用
            'third_party' => 'wechat',
            'nickname'    => $data['nickname'],
            'avatar'      => $data['headimgurl'],
            'union_id'    => $data['unionid'],          //新增，用于微信WEB页登录 与 微信小程序登录 识别同一个用户
            'access_token'    => $token['access_token'],        //access_token过期时间
            'openid'          => $token['openid'],
        ];
        //将用户访问日志写入数据库
        Db::name('dhgxlive_user')->insert($userInfo);
        //$userId = Db::name('dhgxlive_user')->getLastInsID();
        //$userInfo['id'] = $userId;

        //查询用户
        $findUser = Db::table('dhgx_user')->where('union_id', $userInfo['union_id'])->find();
        if ($findUser) {
            $n = Db::table('dhgx_user')->where('id', $findUser['id'])->update(['last_login_time' => time()]);

            session('user', $findUser);
            session('ADMIN_ID', $findUser['id']);
            session('name', $findUser["nickname"]);
        } else {
            //没有这个用户就新增
            $d = $userInfo;
            unset($d['login_time']);
            unset($d['login_ip']);
            $d['last_login_time'] = time();
            $d['user_level'] = 100; //默认用户是普通用户

            Db::table('dhgx_user')->insert($d);
            $userId = Db::name('dhgxlive_user')->getLastInsID();
            $d['id'] = $userId;

            session('user', $d);
            session('ADMIN_ID', $d['id']);
            session('name', $d["nickname"]);
        }
        // 发送POST请求
        //$postResponse = $this->post('https://dhgx.kjdll.cn/wxloginforfkjdllcn', $userInfo);
        //$this->success("ok",'https://dhgx.kjdll.cn:88/wxloginforfkjdllcn',$userInfo);

        /** 修改成后台用户登陆 , 为了让api能使用微信登录后的restAdminController，START*/
        //写入后台管理员session
        //session('user.id', $userId);
        session("__LOGIN_BY_CMF_ADMIN_PW__", null);
        /**修改成后台用户登陆 END*/
        $this->success("登陆成功", "/dhgx/zb");

        $this->redirect("/", 302, '');
    }
}
